package com.unlcn.ils.wms.backend.service.bigscreen.impl;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.unlcn.ils.wms.backend.bo.biBO.BiOverReasonBO;
import com.unlcn.ils.wms.backend.dto.bigscreenDTO.ReasonInfoDTO;
import com.unlcn.ils.wms.backend.enums.OverReasonEnum;
import com.unlcn.ils.wms.backend.enums.TmsUrlEnum;
import com.unlcn.ils.wms.backend.enums.TmsUrlTypeEnum;
import com.unlcn.ils.wms.backend.service.bigscreen.OverReasonService;
import com.unlcn.ils.wms.base.mapper.bigscreen.BiOverReasonMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.BiOverReasonExtMapper;
import com.unlcn.ils.wms.base.mapper.sys.TmsCallHistoryMapper;
import com.unlcn.ils.wms.base.model.bigscreen.BiOverReason;
import com.unlcn.ils.wms.base.model.bigscreen.BiOverReasonExample;
import com.unlcn.ils.wms.base.model.sys.TmsCallHistory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 超期原因分析service
 */
@Service
public class OverReasonServiceImpl implements OverReasonService {

    @Autowired
    private BiOverReasonMapper biOverReasonMapper;

    @Autowired
    private BiOverReasonExtMapper biOverReasonExtMapper;

    @Value("${tms.pickup.host.url}")
    private String propertyUrl;

    @Value("${tms.pickup.host.timeout}")
    private String propertyTime;

    @Value("${tms.encode.key}")
    private String propertyKey;

    @Autowired
    private TmsCallHistoryMapper tmsCallHistoryMapper;

    private Logger LOGGER = LoggerFactory.getLogger(OverReasonServiceImpl.class);

    @Override
    public List<ReasonInfoDTO>  reasonChartCount() {
        // 查询所有超期状态的信息
        List<BiOverReason> biOverReasonList = biOverReasonExtMapper.reasonChartCount();

        // 质损数
        Integer massLoss = 0;
        // 管控数
        Integer missingPart = 0;
        // 暂运数
        Integer stop = 0;
        for (BiOverReason biOverReason : biOverReasonList) {
            switch (biOverReason.getExceptionType()) {
                case "MASS_LOSS":
                    massLoss = biOverReason.getExceptionCount() ;
                    break;
                case "MAN_CTRLS":
                    missingPart = biOverReason.getExceptionCount() ;
                    break;
                case "STOP":
                    stop  = biOverReason.getExceptionCount() ;
                    break;
            }
        }

        List<ReasonInfoDTO> list = new ArrayList<ReasonInfoDTO>();

        ReasonInfoDTO reasonInfoDTO = new ReasonInfoDTO();
        reasonInfoDTO.setName("质损");
        reasonInfoDTO.setValue(massLoss);
        list.add(reasonInfoDTO);

        reasonInfoDTO = new ReasonInfoDTO();
        reasonInfoDTO.setName("管控");
        reasonInfoDTO.setValue(missingPart);
        list.add(reasonInfoDTO);

        reasonInfoDTO = new ReasonInfoDTO();
        reasonInfoDTO.setName("暂运");
        reasonInfoDTO.setValue(stop);
        list.add(reasonInfoDTO);

        return list;
    }


    @Override
    public void addReasonInfo() {

        String strUrl=propertyUrl + TmsUrlEnum.BI_OVERREASON.getText();
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);

        String result = null;

        TmsCallHistory tmsCallHistory=new TmsCallHistory();

        try {
            tmsCallHistory.setTmsUrl(strUrl);
            tmsCallHistory.setPullOrPush(0);
            tmsCallHistory.setCallStartTime(new Date());
            tmsCallHistory.setTmsUrlType(TmsUrlTypeEnum.BI_OVERREASON.getValue());
            tmsCallHistory.setParameters("");
            result = HttpRequestUtil.sendHttpPost(strUrl, headerMap, map, time);

        } catch (Exception e) {
            LOGGER.error("OverReasonServiceImpl.addReasonInfo error : ", e);
            throw new BusinessException("访问tms接口失败");
        }

        try{
            if (StringUtils.isNotBlank(result)) {

                JSONObject jsonObject = JSONObject.parseObject(result);
                String msg = jsonObject.getString("message");
                String records = jsonObject.getString("records");
                Boolean success = jsonObject.getBoolean("success");
                tmsCallHistory.setCallEndTime(new Date());
                tmsCallHistory.setMessage(msg);
                tmsCallHistory.setResultContent(result);

                if (!success) {
                    LOGGER.error("OverReasonServiceImpl callTms error msg: {}", msg);
                    tmsCallHistory.setResultCount(0);
                    tmsCallHistory.setSuccess(success);
                    tmsCallHistoryMapper.insertSelective(tmsCallHistory);
                }

                List<BiOverReasonBO> tmsBOList = JSONArray.parseArray(records, BiOverReasonBO.class);
                tmsCallHistory.setResultCount(tmsBOList.size());
                tmsCallHistory.setSuccess(success);
                tmsCallHistoryMapper.insertSelective(tmsCallHistory);

                SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmSS");
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date());
                String dateStr2 = format2.format(calendar2.getTime());

                tmsBOList.forEach((BiOverReasonBO v) -> {
                    for(int i=0;i<3;i++){
                        //新增
                        BiOverReason biOverReason = new BiOverReason();

                        if(i==0){
                            biOverReason.setExceptionType(OverReasonEnum.LOSSES.getValue());
                            biOverReason.setExceptionCount(Integer.parseInt(Strings.isNullOrEmpty(v.getLosses())?"0":v.getLosses()));
                        }

                        if(i==1){
                            biOverReason.setExceptionType(OverReasonEnum.MAN_CTRLS.getValue());
                            biOverReason.setExceptionCount(Integer.parseInt(Strings.isNullOrEmpty(v.getMan_ctrls())?"0":v.getMan_ctrls()));
                        }

                        if(i==2){
                            biOverReason.setExceptionType(OverReasonEnum.SUSPENDS.getValue());
                            biOverReason.setExceptionCount(Integer.parseInt(Strings.isNullOrEmpty(v.getSuspends())?"0":v.getSuspends()));
                        }

                        biOverReason.setVersion(dateStr2);
                        biOverReasonMapper.insertSelective(biOverReason);
                    }

                });
            }

        }
        catch (Exception e) {
            LOGGER.error("PickDataServiceImpl.addPickData error : ", e);
            throw new BusinessException("保存失败");
        }
    }
}
